from flask import Flask, jsonify
import asyncio
from dajiangdahe import crawl_async as crawl_djdh

from jiangxishuiwen import crawl_jiangxishuiwen, crawl_poyanghu
app = Flask(__name__)

class ApiResponse:
    def __init__(self, data=None, message='', code=200):
        self.data = data
        self.message = message
        self.code = code

    def to_dict(self):
        return {
            'data': self.data,
            'message': self.message,
            'code': self.code
        }
    

# @app.errorhandler(Exception)
# def handle_exception(e):
#     response = ApiResponse(message=str("出现错误，请关闭VPN或者其他方法"), code=500)
#     return response.jsonify()

@app.route('/api/pyh', methods=['GET'])
def get_data_pyh():
    try:
        data = crawl_poyanghu()  # 调用爬虫获取数据
        data = ApiResponse(data, "success").to_dict()
    except Exception as e:
        data = ApiResponse(message=str("出现错误，请关闭VPN或者其他方法"), code=500).to_dict()
        print(e)
    return jsonify(data)  # 返回 JSON 格式的响应

@app.route('/api/jxsw', methods=['GET'])
def get_data_jxsw():
    try:

        data = crawl_jiangxishuiwen()  # 调用爬虫获取数据
        data = ApiResponse(data, "success").to_dict()
    except Exception as e:
        data = ApiResponse(message=str("出现错误，请关闭VPN或者其他方法"), code=500).to_dict()
        print(e)
    # data = crawl_jiangxishuiwen()  # 调用爬虫获取数据
    # data = ApiResponse(data, "success").to_dict()

    return jsonify(data)  # 返回 JSON 格式的响应

@app.route('/api/djdh', methods=['GET'])
async def get_data_djdh():
    try:
        data = await crawl_djdh()  # 调用爬虫获取数据
        data = ApiResponse(data, "success").to_dict()
    except Exception as e:
        data = ApiResponse(message=str("出现错误,请关闭VPN或者其他方法"), code=500).to_dict()
        print(e)
    # data = crawl_jiangxishuiwen()  # 调用爬虫获取数据
    # data = ApiResponse(data, "success").to_dict()

    return jsonify(data)  # 返回 JSON 格式的响应


if __name__ == '__main__':
    app.run(debug=True, port=18080)
